<script lang="ts" setup>
import { useSystemStore } from '@/stores/system'
import { useUserStore } from '@/stores/user'
import { insertUserApi, loginApi, type UserVO } from '@/request/api/user'
import type { ResultType } from '@/type/type'
import { Code } from '@/request/code'
import { RouteNameEnum } from '@/enum'

const systemStore = useSystemStore()
const userStore = useUserStore()
const url = systemStore.getRandomImg()
const router = useRouter()

const formRef = ref()
let code = ref('')
const data = reactive({
  isLogin: true,
  loginForm: {
    email: '',
    password: '',
    code: ''
  },
  rules: {
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      {
        pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
        message: '邮箱格式不正确',
        trigger: 'blur'
      }
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 8, max: 16, message: '密码长度应在8到16位之间', trigger: 'blur' },
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d).+$/,
        message: '密码必须包含英文和数字',
        trigger: 'blur'
      }
    ],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
  }
})
const { loginForm, rules, isLogin } = toRefs(data)

const leftClass =
  'flex w-2/5 max-sm:w-1/3 duration-500 z-50 py-10 px-2 bg-amber-500 justify-between items-center '
const rightClass =
  'flex w-3/5 duration-500 max-sm:w-2/3 z-40 justify-between items-center py-10 px-2 '

const sendForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (code.value !== loginForm.value.code.toUpperCase()) {
      ElMessage.warning('验证码错误!')
      return
    }
    // 表单验证失败
    if (!valid) {
      return
    }
    // 登录
    if (isLogin.value) {
      await loginApi(loginForm.value.email, loginForm.value.password).then(
        (res: ResultType<UserVO>) => {
          if (res.code === Code.SUCCESS) {
            userStore.user = res.data
            userStore.token = res.data.token
            ElMessage.success('登录成功!')
            router.push({ name: RouteNameEnum.HOME })
          }
        }
      )
    } else {
      // 注册
      await insertUserApi(loginForm.value.email, loginForm.value.password)
    }
  })
}
</script>

<template>
  <el-container class="relative w-screen h-screen" direction="vertical">
    <ImageBox :src="url" class="absolute z-0" fit="cover" />
    <el-container class="absolute size-full bg-gray-900/30 z-10" />
    <el-container class="z-20 px-5" direction="vertical">
      <el-header class="flex px-0 items-center">
        <Header />
      </el-header>
      <el-container
        class="text-black z-20 use-second-bg use-transitions-shadow-short use-radius m-auto max-h-96 w-full max-w-[520px] relative"
      >
        <el-container
          :class="isLogin ? leftClass : leftClass + 'translate-x-[150%] max-sm:translate-x-[200%]'"
          direction="vertical"
        >
          <span class="text-xl max-sm:text-sm">
            {{ isLogin ? '没有账号？' : '已有账号？' }}
          </span>
          <a
            class="mb-5 py-1 flex justify-center w-full max-sm:text-xs"
            href="javascript:"
            @click="isLogin = !isLogin"
          >
            {{ isLogin ? '去注册?' : '去登录?' }}
          </a>
        </el-container>
        <el-container
          :class="
            isLogin ? rightClass : rightClass + '-translate-x-[66.66%] max-sm:-translate-x-[50%]'
          "
          direction="vertical"
        >
          <span class="text-2xl pb-10 max-sm:text-xl">{{ isLogin ? '登 录' : '注 册' }}</span>
          <el-form ref="formRef" :model="loginForm" :rules="rules" class="max-sm:text-base">
            <el-form-item class="w-full" prop="email">
              <el-input v-model="loginForm.email" placeholder="邮 箱">
                <template #prefix>
                  <SvgIcon name="email" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w-full" prop="password">
              <el-input
                v-model="loginForm.password"
                class="mt-2 max-sm:text-sm"
                placeholder="密 码"
                show-password
                type="password"
              >
                <template #prefix>
                  <SvgIcon name="lock" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w-full" prop="code">
              <el-input v-model="loginForm.code" class="mt-2 relative" placeholder="验证码">
                <template #prefix>
                  <SvgIcon name="lock" />
                </template>
                <template #suffix>
                  <CodeTemplate
                    :height="28"
                    class="absolute right-0.5"
                    @getCode="(args: string) => (code = args)"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w-full">
              <a
                class="mt-5 use-radius-xs use-transitions-shadow-short flex justify-center border border-amber-500 w-full use-hover-bg"
                href="javascript:"
                @click="sendForm"
              >
                {{ isLogin ? '登 录' : '注 册' }}
              </a>
            </el-form-item>
          </el-form>
        </el-container>
      </el-container>
    </el-container>
  </el-container>
</template>

<style lang="scss" scoped></style>
